<template>
    <div class="store-nearby-container">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <div class="navbar-back" @click="goBack">
                <i class="fas fa-arrow-left"></i>
            </div>
            <div class="navbar-title">附近商店</div>
            <div style="width: 24px;"></div>
        </div>

        <div class="map-container">
            <!-- 高德地图容器 -->
            <div id="map-container" class="map"></div>

            <!-- 搜索栏 -->
            <div class="search-bar">
                <i class="fas fa-search search-icon"></i>
                <input type="text" class="search-input" placeholder="搜索宠物店" v-model="searchQuery" @input="handleSearch">
            </div>

            <!-- 定位按钮 -->
            <div class="location-btn" @click="locateUser">
                <i class="fas fa-location-arrow"></i>
            </div>

            <!-- 商店列表面板 -->
            <div class="store-list-panel">
                <div class="panel-header">
                    <div class="panel-title">附近的宠物店</div>
                    <div class="panel-action" @click="toggleListView">
                        <i class="fas fa-list"></i>
                    </div>
                </div>

                <div class="store-filter">
                    <div v-for="filter in filters" :key="filter.value"
                        :class="['filter-btn', { active: currentFilter === filter.value }]"
                        @click="setFilter(filter.value)">
                        {{ filter.name }}
                    </div>
                </div>

                <div v-if="loading" class="loading-container">
                    <div class="loading-spinner"></div>
                    <div class="loading-text">加载中...</div>
                </div>

                <div v-else-if="filteredStores.length === 0" class="empty-state">
                    <i class="fas fa-store-alt-slash empty-icon"></i>
                    <p>没有找到符合条件的商店</p>
                </div>

                <div v-else class="store-list">
                    <router-link v-for="store in filteredStores" :key="store.storeId" :to="`/store/${store.storeId}`"
                        class="store-card" :id="`store-${store.storeId}`" @click="highlightMarker(store.storeId)">
                        <img class="store-image" :src="store.coverImage || getRandomDefaultImage()" :alt="store.name">
                        <div class="store-content">
                            <div class="store-header">
                                <div class="store-name">{{ store.name }}</div>
                                <div class="store-rating">
                                    <i class="fas fa-star"></i>
                                    <span class="store-rating-score">{{ store.rating.toFixed(1) == 0 ? '暂无评分' :
                                        store.rating.toFixed(1) }}</span>
                                </div>
                            </div>
                            <div class="store-info">
                                <i class="fas fa-map-marker-alt"></i>
                                <span>{{ store.address }}</span>
                            </div>
                            <div class="store-tags">
                                <span class="store-tag" v-for="tag in store.tags" :key="tag.tagId">{{ tag.name }}</span>
                            </div>
                            <div class="store-distance">
                                <span :class="['store-hours', { closed: !isStoreOpen(store.businessHours) }]">
                                    {{ isStoreOpen(store.businessHours) ? '营业中' : '已关闭' }}
                                </span>
                                <span v-if="store.distance" class="distance-value">{{ formatDistance(store.distance)
                                }}</span>
                            </div>
                        </div>
                    </router-link>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import api from '@/network/api';
import { useRouter } from 'vue-router';
import { showDialog } from 'vant';
export default {
    name: 'StoreNearByView',
    setup() {
        const router = useRouter();
        const map = ref(null);
        const stores = ref([]);
        const loading = ref(true);
        const searchQuery = ref('');
        const currentFilter = ref(0);
        const userLocation = ref({ latitude: 0, longitude: 0 });
        const markers = ref([]);
        const filters = ref([
            { name: '全部', value: 0 },
        ]);

        const getRandomDefaultImage = () => {
            const imageNumber = Math.floor(Math.random() * 4) + 1;
            return `/image/store_cover/${imageNumber}.png`;
        };

        const goBack = () => {
            router.back();
        };
        
        const getStoreTags = async (id) => {
            if (!id) return [];
            try {
                const response = await api.getStoreTagsById(id);
                return response.data.data || [];
            } catch (error) {
                console.error(`获取商店 ${id} 的标签失败:`, error);
                return [];
            }
        };

        // 获取商店标签
        const fetchStoreTags = async () => {
            try {
                const response = await api.getStoreTags();
                if (response.data && response.data.data) {
                    const dynamicFilters = response.data.data.map(tag => ({
                        name: tag.name,
                        value: tag.tagId
                    }));
                    filters.value = [...filters.value, ...dynamicFilters];
                }
            } catch (error) {
                console.error('获取商店标签失败:', error);
            }
        };

        // 初始化地图
        const initMap = () => {
            if (!window.AMap) {
                console.error('高德地图API未加载');
                return;
            }

            map.value = new window.AMap.Map('map-container', {
                resizeEnable: true,
                zoom: 13,
                center: [116.397428, 39.90923] // 默认中心点，后续会更新为用户位置
            });

            // 添加地图控件
            map.value.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
                map.value.addControl(new window.AMap.ToolBar());
                map.value.addControl(new window.AMap.Scale());
            });

            // 获取用户位置
            getUserLocation();
        };

        // 获取用户位置
        const getUserLocation = () => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        userLocation.value = {
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude
                        };

                        // 更新地图中心点
                        if (map.value) {
                            map.value.setCenter([userLocation.value.longitude, userLocation.value.latitude]);

                            // 添加用户位置标记
                            new window.AMap.Marker({
                                map: map.value,
                                position: [userLocation.value.longitude, userLocation.value.latitude],
                                icon: new window.AMap.Icon({
                                    size: new window.AMap.Size(25, 34),
                                    image: '//webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                                    imageSize: new window.AMap.Size(25, 34)
                                }),
                                offset: new window.AMap.Pixel(-12, -34)
                            });
                        }

                        // 获取附近商店
                        fetchNearbyStores();
                    },
                    (error) => {
                        console.error('获取位置信息失败:', error);
                        showDialog({
                            title: '提示',
                            message: '获取位置信息失败，将尝试获取所有商店',
                        });
                        fetchStores(); // 即使获取位置失败也获取商店列表
                    },
                    { enableHighAccuracy: true }
                );
            } else {
                console.error('浏览器不支持地理位置');
                fetchStores();
            }
        };

        // 定位用户
        const locateUser = () => {
            if (map.value && userLocation.value.latitude && userLocation.value.longitude) {
                map.value.setCenter([userLocation.value.longitude, userLocation.value.latitude]);
                map.value.setZoom(14);
            } else {
                getUserLocation();
            }
        };

        // 获取附近的商店
        const fetchNearbyStores = async () => {
            loading.value = true;
            try {
                const params = {};
                params.tagId = currentFilter.value;


                const response = await api.getNearbyStores(
                    userLocation.value.latitude,
                    userLocation.value.longitude,
                    5, // 5公里范围内
                    params
                );

                if (response.data && response.data.data) {
                    const storesData = response.data.data || [];
                    stores.value = await Promise.all(storesData.map(async store => {
                        store.tags = await getStoreTags(store.storeId);
                        // 计算距离 (如果后端没有提供距离信息)
                        if (!store.distance && userLocation.value.latitude && userLocation.value.longitude) {
                            store.distance = calculateDistance(
                                userLocation.value.latitude,
                                userLocation.value.longitude,
                                store.latitude,
                                store.longitude
                            );
                        }
                        return store;
                    }));

                    // 添加商店标记到地图
                    addStoreMarkers();
                }
            } catch (error) {
                console.error('获取附近商店失败:', error);
                showDialog({
                    title: '提示',
                    message: '获取附近商店失败，将尝试获取所有商店',
                });
                fetchStores();
            } finally {
                loading.value = false;
            }
        };

        // 获取商店列表
        const fetchStores = async () => {
            loading.value = true;
            try {
                const response = await api.getStores(currentFilter.value || 0);

                if (response.data && response.data.data) {
                    const storesData = response.data.data || [];
                    stores.value = await Promise.all(storesData.map(async store => {
                        store.tags = await getStoreTags(store.storeId);
                        // 计算距离 (如果后端没有提供距离信息)
                        if (!store.distance && userLocation.value.latitude && userLocation.value.longitude) {
                            store.distance = calculateDistance(
                                userLocation.value.latitude,
                                userLocation.value.longitude,
                                store.latitude,
                                store.longitude
                            );
                        }
                        return store;
                    }));

                    // 添加商店标记到地图
                    addStoreMarkers();
                }
            } catch (error) {
                console.error('获取商店列表失败:', error);
            } finally {
                loading.value = false;
            }
        };

        // 添加商店标记到地图
        const addStoreMarkers = () => {
            if (!map.value) return;

            // 清除现有标记
            markers.value.forEach(marker => {
                map.value.remove(marker);
            });
            markers.value = [];

            // 添加新标记
            stores.value.forEach(store => {
                if (store.latitude && store.longitude) {
                    const marker = new window.AMap.Marker({
                        map: map.value,
                        position: [store.longitude, store.latitude],
                        icon: new window.AMap.Icon({
                            size: new window.AMap.Size(30, 30),
                            image: '//webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                            imageSize: new window.AMap.Size(30, 30)
                        }),
                        offset: new window.AMap.Pixel(-15, -30),
                        extData: { storeId: store.storeId }
                    });

                    // 添加点击事件
                    marker.on('click', () => {
                        highlightMarker(store.storeId);

                        // 滚动到对应的商店项
                        const storeElement = document.getElementById(`store-${store.storeId}`);
                        if (storeElement) {
                            storeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    });

                    markers.value.push(marker);
                }
            });
        };

        // 高亮标记
        const highlightMarker = (storeId) => {
            markers.value.forEach(marker => {
                const extData = marker.getExtData();
                if (extData && extData.storeId === storeId) {
                    marker.setIcon(new window.AMap.Icon({
                        size: new window.AMap.Size(35, 35),
                        image: '//webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                        imageSize: new window.AMap.Size(35, 35)
                    }));
                    marker.setOffset(new window.AMap.Pixel(-17.5, -35));

                    // 将地图中心移动到该标记
                    map.value.setCenter(marker.getPosition());
                } else {
                    marker.setIcon(new window.AMap.Icon({
                        size: new window.AMap.Size(30, 30),
                        image: '//webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                        imageSize: new window.AMap.Size(30, 30)
                    }));
                    marker.setOffset(new window.AMap.Pixel(-15, -30));
                }
            });
        };

        // 计算两点之间的距离（使用Haversine公式）
        const calculateDistance = (lat1, lon1, lat2, lon2) => {
            const R = 6371; // 地球半径，单位为公里
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLon = (lon2 - lon1) * Math.PI / 180;
            const a =
                Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return R * c;
        };

        // 格式化距离显示
        const formatDistance = (distance) => {
            if (distance === null || distance === undefined) return '未知';
            if (distance < 1) {
                return `${(distance * 1000).toFixed(0)}m`;
            }
            return `${distance.toFixed(1)}km`;
        };

        // 根据过滤条件和搜索词过滤商店
        const filteredStores = computed(() => {
            let result = stores.value;

            // 应用搜索过滤
            if (searchQuery.value) {
                const query = searchQuery.value.toLowerCase();
                result = result.filter(store =>
                    store.name.toLowerCase().includes(query) ||
                    store.address.toLowerCase().includes(query) ||
                    store.tags.some(tag => tag.name.toLowerCase().includes(query))
                );
            }

            return result;
        });

        // 设置过滤条件
        const setFilter = (filter) => {
            currentFilter.value = filter;
            if (userLocation.value.latitude && userLocation.value.longitude) {
                fetchNearbyStores();
            } else {
                fetchStores();
            }
        };

        // 处理搜索
        const handleSearch = () => {
            // 可以在这里实现搜索防抖等逻辑
        };

        // 切换列表视图
        const toggleListView = () => {
            const panel = document.querySelector('.store-list-panel');
            if (panel) {
                panel.classList.toggle('expanded');
            }
        };

        // 判断商店是否营业中
        const isStoreOpen = (businessHours) => {
            if (!businessHours || typeof businessHours !== 'string') return false;

            const now = new Date();
            // JS getDay(): Sun=0, Mon=1, ..., Sat=6.
            // 营业时间格式似乎是 Mon=1, ..., Sat=6, Sun=7.
            let dayOfWeek = now.getDay();
            if (dayOfWeek === 0) {
                dayOfWeek = 7; // 将周日转换为7以匹配格式
            }

            const currentTotalMinutes = now.getHours() * 60 + now.getMinutes();

            try {
                const schedules = businessHours.split(',');

                for (const schedule of schedules) {
                    const firstColonIndex = schedule.indexOf(':');
                    if (firstColonIndex === -1) continue;

                    const daysPart = schedule.substring(0, firstColonIndex);
                    const hoursPart = schedule.substring(firstColonIndex + 1);

                    let dayStart, dayEnd;
                    if (daysPart.includes('-')) {
                        [dayStart, dayEnd] = daysPart.split('-').map(Number);
                    } else {
                        dayStart = dayEnd = Number(daysPart);
                    }

                    if (dayOfWeek >= dayStart && dayOfWeek <= dayEnd) {
                        const [timeStartStr, timeEndStr] = hoursPart.split('-');
                        const [startHour, startMinute] = timeStartStr.split(':').map(Number);
                        const [endHour, endMinute] = timeEndStr.split(':').map(Number);

                        const openTimeInMinutes = startHour * 60 + startMinute;
                        const closeTimeInMinutes = endHour * 60 + endMinute;

                        if (currentTotalMinutes >= openTimeInMinutes && currentTotalMinutes <= closeTimeInMinutes) {
                            return true; // 商店正在营业
                        }
                    }
                }
            } catch (error) {
                console.error('解析营业时间出错:', businessHours, error);
                return false; // 解析失败则认为已关闭
            }

            return false; // 商店已关闭
        };

        onMounted(() => {
            // 获取商店标签
            fetchStoreTags();

            // 加载高德地图API
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://webapi.amap.com/maps?v=2.0&key=6753f35feab64d68da6a1e51fa2054f6&plugin=AMap.Geolocation,AMap.ToolBar,AMap.Scale';
            script.onload = () => {
                initMap();
            };
            document.head.appendChild(script);
        });

        onUnmounted(() => {
            // 销毁地图实例
            if (map.value) {
                map.value.destroy();
            }
        });

        return {
            stores,
            loading,
            searchQuery,
            currentFilter,
            filters,
            filteredStores,
            setFilter,
            handleSearch,
            formatDistance,
            locateUser,
            highlightMarker,
            toggleListView,
            getRandomDefaultImage,
            isStoreOpen,
            goBack
        };
    }
}
</script>

<style scoped>
.store-nearby-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f8f9fa;
}

.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: white;
    border-bottom: 1px solid #e9ecef;
    z-index: 10;
}

.navbar-back {
    color: #333;
    font-size: 16px;
}

.navbar-title {
    font-weight: bold;
    font-size: 18px;
}

.map-container {
    flex: 1;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

#map-container {
    height: 30vh;
    flex-shrink: 0;
}

.map {
    width: 100%;
    height: 100%;
    background-color: #f1f5f9;
    cursor: pointer;
}

.search-bar {
    position: absolute;
    top: 15px;
    left: 15px;
    right: 15px;
    display: flex;
    align-items: center;
    background-color: white;
    border-radius: 8px;
    padding: 10px 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 5;
}

.search-icon {
    color: #94a3b8;
    margin-right: 10px;
}

.search-input {
    border: none;
    outline: none;
    flex: 1;
    font-size: 14px;
}

.location-btn {
    position: absolute;
    bottom: 30px;
    right: 15px;
    width: 40px;
    height: 40px;
    background-color: #f8fafc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    color: #3490dc;
    z-index: 5;
    cursor: pointer;
}

.store-list-panel {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #f8fafc;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
    z-index: 5;
    transition: max-height 0.3s ease;
}

.store-list-panel.expanded {
    max-height: 80%;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.panel-title {
    font-size: 18px;
    font-weight: bold;
    color: #2d3748;
}

.panel-action {
    color: #4a5568;
    cursor: pointer;
}

.store-filter {
    display: flex;
    padding-bottom: 15px;
    margin-bottom: 5px;
    overflow-x: auto;
    border-bottom: 1px solid #f1f5f9;
    scrollbar-width: none;
}

.store-filter::-webkit-scrollbar {
    display: none;
}

.filter-btn {
    padding: 8px 16px;
    background-color: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    color: #4a5568;
    margin-right: 10px;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
}

.filter-btn:hover {
    border-color: #3490dc;
    color: #3490dc;
}

.filter-btn.active {
    background-color: #3490dc;
    color: white;
    border-color: #3490dc;
}

.store-list {
    flex: 1;
    padding-top: 10px;
    overflow: auto;
    padding-bottom: 60px !important;
}

.store-card {
    display: flex;
    padding: 16px;
    background-color: white;
    border-radius: 12px;
    margin: 0 4px 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.store-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.12);
}

.store-image {
    width: 90px;
    height: 90px;
    border-radius: 10px;
    object-fit: cover;
    margin-right: 16px;
    flex-shrink: 0;
}

.store-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.store-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.store-name {
    font-weight: 600;
    font-size: 17px;
    color: #1e293b;
    margin-right: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.store-rating {
    display: flex;
    align-items: center;
    color: #f59e0b;
    font-size: 14px;
    font-weight: 600;
    flex-shrink: 0;
}

.store-rating-score {
    margin-left: 4px;
    color: #1e293b;
}

.store-info {
    font-size: 13px;
    color: #64748b;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.store-info i {
    margin-right: 6px;
    color: #94a3b8;
}

.store-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: auto;
    padding-bottom: 8px;
}

.store-tag {
    display: inline-block;
    padding: 3px 10px;
    background-color: #f1f5f9;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 500;
    color: #475569;
}

.store-distance {
    font-size: 13px;
    color: #4a5568;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
}

.distance-value {
    font-weight: 500;
}

.store-hours {
    font-weight: 500;
    color: #10b981;
}

.store-hours.closed {
    color: #ef4444;
}


.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100px;
    padding: 20px 0;
}

.loading-spinner {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3490dc;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    color: #718096;
    font-size: 14px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100px;
    padding: 20px 0;
    color: #a0aec0;
}

.empty-icon {
    font-size: 32px;
    margin-bottom: 10px;
}
</style>
